package com.jhgsys.internal.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.enums.TenantBusTypeEnum;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.system.dto.TenantDto;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.ITenantService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @className TenantController
 * @description 公司管理
 * @author DingHaiTao
 * @date: 2024/7/17 16:02
*/
@Slf4j
@Validated
@RestController
@RequestMapping("tenant")
public class TenantController extends BaseController {

    @Autowired
    private ITenantService tenantService;

    @PostMapping("creatAppId")
    public FebsResponse creatAppId() {
        return new FebsResponse().success().data(FebsUtil.uuid());
    }

    @PostMapping("creatAppSecret")
    public FebsResponse creatAppSecret() {
        return new FebsResponse().success().data(FebsUtil.uuid());
    }

    @Log("新增公司")
    @PostMapping
    @ResponseBody
    @RequiresPermissions(value={"tenant:add"},logical= Logical.OR)
    public FebsResponse addTenant(@RequestBody @Valid TenantDto tenantDto) throws FebsException {
        Tenant tenantParam = new Tenant();
        tenantParam.setTenantCode(tenantDto.getTenantCode());
        tenantParam.setTenantCode(tenantDto.getTenantCode());
        List<TenantDto> tenantList = this.tenantService.findTenantList(tenantParam);
        if(null != tenantList && tenantList.size() > 0){
           throw new FebsException("公司名称已存在");
        }
        tenantParam = new Tenant();
        tenantList = new ArrayList<>();
        tenantParam.setBusinessCode(tenantDto.getBusinessCode());
        tenantList = this.tenantService.findTenantList(tenantParam);
        if(null != tenantList && tenantList.size() > 0){
            throw new FebsException("业务编码已存在");
        }
        try {
            //获取当前用户
            tenantDto.setCreatedBy(getCurrentUser().getUserName());
            this.tenantService.createTenant(tenantDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增公司失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("删除公司")
    @GetMapping("delete/{tenantIds}")
    @RequiresPermissions(value={"tenant:delete"},logical= Logical.OR)
    public FebsResponse deleteTenants(@NotBlank(message = "{required}") @PathVariable String tenantIds) throws FebsException {
        try {
            Tenant tenant = new Tenant();
            // 获取当前用户
            tenant.setDeletedBy(getCurrentUser().getUserName());
            tenant.setDeletedTime(new Date());
            tenant.setDeletedFlg(FebsConstant.INVALID);
            String[] ids = tenantIds.split(StringPool.COMMA);
            this.tenantService.updateTenantDeletedFlg(ids, tenant);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除公司失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改公司")
    @PostMapping("update")
    @ResponseBody
    @RequiresPermissions(value={"tenant:update"},logical= Logical.OR)
    public FebsResponse updateTenant(@RequestBody @Valid TenantDto tenantDto) throws FebsException {
        if (StringUtils.isBlank(tenantDto.getTenantId())) {
            throw new FebsException("公司主键丢失");
        }
//        Tenant tenantParam = new Tenant();
//        List<TenantDto> collect = new ArrayList<>();
//        tenantParam.setTenantCode(tenantDto.getTenantCode());
//        List<TenantDto> tenantList = this.tenantService.findTenantList(tenantParam);
//        log.info("tenantList >> {}",tenantList);
//        if(null != tenantList && tenantList.size() > 0){
//           collect = tenantList.stream().filter(p -> !tenantDto.getTenantId().equals(p.getTenantId())).collect(Collectors.toList());
//        }
//        log.info("collect >> {}",collect);
//        if(null != collect && collect.size() > 0){
//            throw new FebsException("公司名称已存在");
//        }
//        tenantParam = new Tenant();
//        tenantList = new ArrayList<>();
//        collect = new ArrayList<>();
//        tenantParam.setBusinessCode(tenantDto.getBusinessCode());
//        tenantList = this.tenantService.findTenantList(tenantParam);
//        if(null != tenantList && tenantList.size() > 0){
//            collect = tenantList.stream().filter(p -> !tenantDto.getTenantId().equals(p.getTenantId())).collect(Collectors.toList());
//        }
//        if(null != collect && collect.size() > 0){
//            throw new FebsException("业务编码已存在");
//        }

        try {
            // 获取当前用户
            tenantDto.setUpdatedBy(getCurrentUser().getUserName());
            this.tenantService.updateTenant(tenantDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改公司失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("check/{tenantName}")
    public boolean checkTenantName(@NotBlank(message = "{required}") @PathVariable String tenantName, String tenantId) {
        TenantDto tenantDto = new TenantDto();
        tenantDto.setTenantName(tenantName);
        return this.tenantService.findByName(tenantName) == null || StringUtils.isNotBlank(tenantId);
    }

    private IPage<Tenant> getTenantIPage(Tenant tenant, QueryRequest request) {
        IPage<Tenant> pageData = this.tenantService.findTenantPage(tenant, request);
        return pageData;
    }




    @GetMapping("list")
    @RequiresPermissions(value={"tenant:view"},logical= Logical.OR)
    public FebsResponse tenantList(Tenant tenant, QueryRequest request) {
        if(!hasHeadCompanyRole()){
            tenant.setTenantId(getCurrentTenantId());
        }
        Map<String, Object> dataTable = getDataTable(getTenantIPage(tenant, request));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping("getTenantTypeSelect")
    @RequiresPermissions("tenant:view")
    public FebsResponse getTenantTypeSelect() {
        return new FebsResponse().success().data(TenantBusTypeEnum.dictItemList());
    }


    @GetMapping("getTenantSelect")
    @RequiresPermissions("tenant:view")
    public FebsResponse getTenantSelect() {
        List<TenantDto> tenantList =  new ArrayList<>();
        //总公司权限
        if (hasHeadCompanyRole()) {
            tenantList = getTenantList();
        }
        return new FebsResponse().success().data(tenantList);
    }

    @GetMapping("excel")
    @RequiresPermissions("tenant:export")
    public void export(QueryRequest queryRequest, Tenant tenant, HttpServletResponse response) throws FebsException {
        try {
            List<Tenant> tenants = this.tenantService.findTenantPage(tenant, queryRequest).getRecords();
            ExcelKit.$Export(User.class, response).downXlsx(tenants, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改公司启用/停用状态")
    @PostMapping("updateStatus")
    @RequiresPermissions(value={"tenant:update"},logical= Logical.OR)
    public FebsResponse updateStatus(Tenant tenant) throws FebsException {
        try {
            if (StringUtils.isBlank(tenant.getTenantId())) {
                return new FebsResponse().fail().message("公司Id不能为空");
            }
            if (StringUtils.isBlank(tenant.getStatus())) {
                return new FebsResponse().fail().message("更新状态不能为空");
            }
            User currentUser = getCurrentUser();
            Tenant updateTenant = new Tenant();
            updateTenant.setTenantId(tenant.getTenantId());
            updateTenant.setStatus(tenant.getStatus());
            updateTenant.setUpdatedBy(currentUser.getUserName());
            updateTenant.setUpdatedTime(new Date());
            this.tenantService.updateStatus(updateTenant);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改公司状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

}
